package com.shark.commons.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.shark.commons.web.model.SystemContext;


public class SystemContextInterceptor extends HandlerInterceptorAdapter {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    	
    	setPageParamContext(request);
    	
        return true;
    }
    
    @Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    	clearPageParamContext();
    	
		super.afterCompletion(request, response, handler, ex);
	}

    /**
     * 设置TheadLocal数据
     * 分页参数
     * 排序参数
     * @param request
     */
    public void setPageParamContext(HttpServletRequest request) {
    	//分页
		String pageNum = request.getParameter("pageNumber") ;
		String pageSize = request.getParameter("pageSize") ;
		
		//排序
		String sort = request.getParameter("sort") ;
		String order = request.getParameter("order") ;
		String orderby = request.getParameter("orderby") ;
		
		
		if(null != pageNum && !"".equals(pageNum))
			SystemContext.setPageNum(Integer.parseInt(pageNum));
		
		if(null != pageSize && !"".equals(pageSize))
			SystemContext.setPageSize(Integer.parseInt(pageSize));
		
		if(null != sort && !"".equals(sort))
			SystemContext.setSort(sort);
		
		if(null != order && !"".equals(order))
			SystemContext.setOrder(order);
		
		if(null != orderby && !"".equals(orderby))
			SystemContext.setOrderby(orderby);
    }
    
    
    /**
     * 清楚TheadLocal的数据
     */
    public void clearPageParamContext() {
    	SystemContext.removeOrder();
    	SystemContext.removeOrderby();
    	SystemContext.removePageNum();
    	SystemContext.removePageSize();
		SystemContext.removeSort();
    }



}
